package org.rocket.spring.security.browser.authentication;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author He Peng
 * @create 2018-01-22 1:33
 * @update 2018-01-22 1:33
 * @updatedesc : 更新说明
 * @see
 */

@Component
public class MyUserDetailsService implements UserDetailsService {

    private static final Logger LOG = LoggerFactory.getLogger(MyUserDetailsService.class);

    private static final Map<String , User> MOCK_USER_DB = new HashMap<>();

    @Autowired
    private PasswordEncoder passwordEncoder;

    static {
        MOCK_USER_DB.put("tom" , null);
        MOCK_USER_DB.put("rose" , null);
        MOCK_USER_DB.put("jerry" , null);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LOG.info("MyUserDetailsService is work , username ==> {} " , username);
        if (! MOCK_USER_DB.containsKey(StringUtils.trim(username))) {
            throw new UsernameNotFoundException(username + "用户不存在");
        }

        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("user");
        String encodePassword = this.passwordEncoder.encode("password");
        User user = new User(username , encodePassword , true , true , true , true , authorities);
        MOCK_USER_DB.put(username , user);
        LOG.info("encode password ==> {} " , user.getPassword());
        return user;
    }
}
